import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { availableMonitors, cursorPosition, getCurrentWindow, PhysicalPosition, PhysicalSize } from '@tauri-apps/api/window';
import { useCallback, useEffect, useState } from 'react';
import './App.css';
import Layout from './Layout';
import { message } from 'antd';
import { setMessage } from './utils/message';

function App() {
  const [visible, setVisible] = useState(false);
  const [_message, msgCtxHolder] = message.useMessage();
  const showPanel = async () => {
    const cuPos = await cursorPosition();
    const monitors = await availableMonitors();
    let monitor = monitors.find(
      (m) => m.position.x <= cuPos.x && m.position.y <= cuPos.y && m.position.x + m.size.width >= cuPos.x && m.position.y + m.size.height >= cuPos.y
    );
    const win = getCurrentWindow();
    const screenHeight = monitor.size.height;
    const height = 292 * monitor.scaleFactor;
    win.setPosition(new PhysicalPosition(monitor.position.x, monitor.position.y + screenHeight - height));
    win.setSize(new PhysicalSize(monitor.size.width, height));
    await invoke('show_panel');
    await new Promise(setTimeout);
    setVisible(true);
  };

  const hidePanel = useCallback(async () => {
    setVisible(false);
    invoke('hide_panel');
  }, []);

  useEffect(() => {
    setMessage(_message);
  }, [_message]);

  useEffect(() => {
    showPanel();
    // 失去焦点隐藏面板
    window.addEventListener('blur', () => {
      hidePanel();
    });
    // 监听快捷键显示或隐藏面板
    let unListenShortcut;
    listen('trigger-shortcut', async () => {
      const window = getCurrentWindow();
      const visible = await window.isVisible();
      if (visible) {
        await hidePanel();
      } else {
        await showPanel();
      }
    }).then((unListen) => {
      unListenShortcut = unListen;
    });
    // esc隐藏面板
    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') {
        invoke('hide_panel');
      }
    });
    // root下注入缩放系数
    document.documentElement.style.setProperty('--dp', 1 / window.devicePixelRatio);
    document.documentElement.style.setProperty('--dpx', 1 / window.devicePixelRatio + 'px');
    return () => {
      unListenShortcut?.();
    };
  }, []);
  return (
    <>
      {msgCtxHolder}
      <Layout visible={visible} hidePanel={hidePanel} />
      <button style={{ position: 'fixed', left: '200%' }} tabIndex={1} />
    </>
  );
}

export default App;
